package com.shujia.mr.tuijian;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/*
    tom hello hadoop cat

    <0L,"tom hello hadoop cat">

    map输出：
    <"tom-hello",1>
    <"tom-hadoop",1>
    <"tom-cat",1>
    <"hello-hadoop",-1>
    <"hello-cat",-1>
    <"hadoop-cat",-1>

   利用String类中的compareTo()方法


 */
public class RecommendMap extends Mapper<LongWritable, Text, Text, LongWritable> {
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        String line = value.toString(); //"tom hello hadoop cat"
        String[] persons = line.split(" "); // ["tom","hello","hadoop","cat"]
//        for (int j = 1; j < persons.length; j++) {
//            //需要将persons[0]与persons[j]进行比较，得到一个顺序
//            String new_key = keyCompare(persons[0], persons[j]);
//            context.write(new Text(new_key), new LongWritable(1L));
//            for (int b = j + 1; b < persons.length; b++) {
//                //需要将persons[0]与persons[j]进行比较，得到一个顺序
//                String new_key2 = keyCompare(persons[j], persons[b]);
//                context.write(new Text(new_key2), new LongWritable(-1L));
//            }
//        }

        for (int i = 0; i < persons.length; i++) {
            for (int j = i + 1; j < persons.length; j++) {
                if (i == 0) {
                    String new_key = keyCompare(persons[i], persons[j]);
                    context.write(new Text(new_key), new LongWritable(1L));
                } else {
                    String new_key = keyCompare(persons[i], persons[j]);
                    context.write(new Text(new_key), new LongWritable(-1L));
                }
            }
        }

    }

    // p1: hadoop p2:hello  --> hadoop-hello
    // p1: hello  p2:hadoop --> hadoop-hello
    public String keyCompare(String p1, String p2) {
        if (p1.compareTo(p2) > 0) {
            return p2 + "-" + p1;
        } else {
            return p1 + "-" + p2;
        }
    }

}
